<template>
  <div>
    <el-upload
      list-type="picture-card"
      :limit="1"
      action="#"
      :http-request="load"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :before-upload="beforeUpload"
      :on-change="changeFile"
      :file-list="fileList"
      :class="{ disabled: fileComputed }"
    >
      <i class="el-icon-plus"></i>
    </el-upload>
    <el-progress
      v-if="showPercent"
      style="width: 180px"
      :percentage="percent"
    />
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>
<script>
import COS from "cos-js-sdk-v5"; //引入腾讯云cos包
var cos = new COS({
  SecretId: "AKIDDHApFCwRimcJp7AzZvFLDvRmunSthJiU", // 身份识别 ID
  SecretKey: "d4KgsulT0KSWCk5D8oIZcR3XpulQs79y", // 身份密钥
});
export default {
  data() {
    return {
      fileList: [], //图片地址设置为数组
      dialogImageUrl: "",
      dialogVisible: false,
      currentFileUid: null, //记录当前正在上传的uid
      showPercent: false,
      percent: 0, //记录进度条百分比
    };
  },
  computed: {
    fileComputed() {
      return this.fileList.length === 1;
    },
  },
  methods: {
    //图片预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    //图片删除
    handleRemove(file, fileList) {
      //file要删除的图片
      this.fileList = this.fileList.filter((item) => item.uid !== file.uid); //uid上传文件自动加的属性
    },
    //效验上传图片类型
    beforeUpload(file) {
      //   先检查文件类型
      const types = ["image/jpeg", "image/gif", "image/bmp", "image/png"];
      if (!types.some((item) => item === file.type)) {
        //如果不存在我们规定的类型
        this.$message.error("图片上传格式不正确");
        return false;
      }

      //检查文件大小 5M 1M（兆）=1024KB 1KB =1024B
      const maxSize = 5 * 1024 * 1024;
      if (file.size > maxSize) {
        this.$message.error("文件大小不能超过5兆");
        return false;
      }
      this.currentFileUid = file.uid;
      this.showPercent = true;
      return true; //这样才会认为通过条件可以继续上传
    },
    //上传动作 可以覆盖默认的上传行为，可以自定义上传的实现
    load(params) {
      if (params.file) {
        //有文件进行上传操作
        cos.putObject(
          {
            //上传到腾讯云
            Bucket: "breeze-1315362973",
            Region: "ap-shanghai",
            Key: params.file.name,
            Body: params.file, //要上传的文件对象
            StorageClass: "STANDARD", // 上传的模式类型 直接默认 标准模式即可
            onProgress: (progressData) => {
              console.log(progressData);
              //进度的回调函数
              this.percent = progressData.percent * 100;
            },
          },
          (err, data) => {
            // console.log(err || data);
            if (!err && data.statusCode === 200) {
              //上传成功，处理返回数据
              //将上传成功的地址回写到了fileList
              this.fileList = this.fileList.map((item) => {
                if (item.uid === this.currentFileUid) {
                  return { url: "http://" + data.Location, upload: true };
                  //upload为true表示这样图片已经上传完毕
                }
                return item;
              });
              setTimeout(() => {
                this.showPercent = false;
                this.percent = 0;
              }, 1000);
            }
          }
        );
      }
    },
    //上传图片
    changeFile(file, fileList) {
      this.fileList = fileList.map((item) => item);
      //这里上传成功才会，数据才会上传显示==》腾讯云
    },
  },
};
</script>
 <style scope>
.disabled .el-upload--picture-card {
  display: none;
}
</style>
